<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Cache;

/**
 * 图片直播作品表
 * Class ArticleModel
 * @package app\common\model
 */
class PictureLiveWorks extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'picture_live_works';

    /**
     * 关联新闻类型
     */
    public function conType()
    {
        return $this->hasOne(NewsType::class, 'id', 'type_id');
    }


    /**
     * 图片直播，上传图片(批量上传)
     * @param user_id 用户id  可选
     * @param act_id int 活动id
     * @param content string json 格式   [{"img":"picture_live\/2023-05-17\/zsCwGEDXx2OyVuWpJx6EqSCZTwNEkqUyErUtxYYP.png","width":260,"height":260,"ratio":"260x260","size":7735},{"img":"picture_live\/2023-05-18\/zsCwGE1111111111111111111111.png","width":260,"height":260,"ratio":"260x260","size":7735}]
     */
    public function batchAdd($act_id, $user_id, $content, $status)
    {
        $content = json_decode($content, true);
        $data = [];
        foreach ($content as $key => $val) {
            $data[$key]['serial_number'] = $this->getSerialNumber('P');
            $data[$key]['user_id'] = $user_id;
            $data[$key]['act_id'] = $act_id;
            $data[$key]['cover'] = str_replace('.', '_cover.', $val['img']);
            $data[$key]['img'] = $val['img'];
            $data[$key]['thumb_img'] = str_replace('.', '_thumb.', $val['img']);
            $data[$key]['width'] = $val['width'];
            $data[$key]['height'] = $val['height'];
            $data[$key]['size'] = $val['size'];
            $data[$key]['ratio'] = $val['ratio'];
            $data[$key]['way'] = 2;
            $data[$key]['status'] = $status;
            $data[$key]['create_time'] = date('Y-m-d H:i:s');
            $data[$key]['change_time'] = date('Y-m-d H:i:s');
        }
        $this->insert($data);
    }


    /**
     * 获取总投票量
     * @param act_id 大赛id
     */
    public function getTotalVoteNumber($act_id)
    {
        return $this->where('act_id', $act_id)->where('status', 1)->sum('vote_num');
    }

    /**
     * 获取作品编号
     * @param  letter 作品编号
     */
    public function getSerialNumber($letter)
    {
        for ($i = 1; $i < 10; $i++) {
            $serial_number = $letter . get_rnd_number(8);

            $is_exists = $this->where('serial_number', $serial_number)->first();

            if (!$is_exists) {
                return $serial_number;
            }
            continue;
        }

        throw new \Exception('条形码获取有误，请联系管理员处理'); //获取10次都获取不到，就不在获取
    }

    /**
     * 获取作品数量
     * @param act_id 活动id
     * @param status  int 状态    1.已通过   2.未通过   3.未审核(默认)  4.已撤销， 5已删除 6.已违规
     */
    public function getWorksNumber($act_id, $status = [])
    {
        return $this->where('act_id', $act_id)->where(function ($query) use ($status) {
            if ($status) {
                $status = !is_array($status) ? explode(',', $status) : $status;
                $query->whereIn('status', $status);
            }
        })->where('is_del', 1)
            ->count();
    }

    /**
     * 更新浏览量
     *
     * @param id 作品id  
     * @param number 多少次更新一次
     * @param second 大于秒更新一次（取决于后一次请求事件）
     */
    public function updateBrowseNumber($id, $number = 100, $second = 300)
    {
        if ($number == 1) {
            return $this->where('id', $id)->increment('browse_num', 1);
        }

        $key = $id . 'contest_activity_browse_number';
        $res = Cache::pull($key); //从缓存中获取缓存项然后删除，使用 pull 方法，如果缓存项不存在的话返回 null
        $data = [];
        if (empty($res)) {
            $data['number'] = 1;
            $data['create_time'] = time();
            Cache::put($key, $data, 3600 * 24);
        } else {
            //数据大于50或者时间超过5分钟，则更新一次数据
            if ($res['number'] >= $number || time() - $res['create_time'] >= $second) {
                return $this->where('id', $id)->increment('browse_num', $res['number'] + 1);
            } else {
                $data['number'] = $res['number'] + 1;
                $data['create_time'] = $res['create_time'];
                Cache::put($key, $data, 3600 * 24);
            }
        }
        return true;
    }


    /**
     * 列表
     * @param act_id int 活动id
     * @param user_id int 用户id
     * @param status int 状态    1.已通过   2.未通过   3.未审核(默认)  4.已撤销
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(文章标题)
     * @param start_time datetime 开始时间(开始)
     * @param end_time datetime 结束时间(开始)
     * @param sort 排序方式  1 默认  2 浏览量  3 点赞
     * @param order 排序方式  1 正序 2倒序
     * @param is_vote 是否查询点赞过的图片  1 是 2否
     */
    public function lists($field = null, $act_id = null, $user_id = null, $keywords = null, $status = null, $start_time = null, $end_time = null, $is_vote = 2, $sort = 1, $order = 2, $limit = 10)
    {
        if (empty($field)) {
            $field = ['id', 'act_id', 'user_id', 'title', 'cover', 'img', 'thumb_img', 'width', 'height', 'size', 'ratio', 'browse_num', 'vote_num', 'status', 'reason', 'way', 'create_time'];
        }
        $vote_works_id_all = [];
        if ($is_vote == 1) {
            $pictureLiveVoteModel = new PictureLiveVote();
            //我的活动数据
            $vote_works_id_all = $pictureLiveVoteModel->where('user_id', $user_id)->where(function ($query) use ($act_id) {
                if ($act_id) {
                    $query->where('act_id', $act_id);
                }
            })->groupBy('works_id')->pluck('works_id')->toArray(); //先只允许看前台上传的
        }
        //排序方式
        $order = $order == 1 ? 'asc' : 'desc';
        if ($sort == 2) {
            $sort_way = 'browse_num ' . $order;
        } elseif ($sort == 3) {
            $sort_way = 'vote_num ' . $order;
        } else {
            $sort_way = 'id ' . $order;
        }
        $res = $this->select($field)
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('title', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($user_id, $status, $start_time, $end_time, $is_vote, $vote_works_id_all) {
                //查询点赞不能查询用户id
                if ($user_id && $is_vote == 2) {
                    $query->where('user_id', $user_id);
                }
                if ($status) {
                    $status = !is_array($status) ? explode(',', $status) : $status;
                    $query->whereIn('status', $status);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
                if ($is_vote == 1) {
                    $query->whereIn('id', $vote_works_id_all); //如果要查询点赞的，必须在点赞列表中
                }
            })
            ->where('act_id', $act_id)
            ->whereNotIn('status', [5, 6]) //删除和违规的图片都不允许看
            ->where('is_del', 1)
            ->orderByRaw($sort_way)
            ->paginate($limit)
            ->toArray();
        $controllerObj = new Controller();
        $res = $controllerObj->disPageData($res);
        return $res;
    }




    /**
     * 详情
     * @param id int 直播id
     * @param status int 状态    1.已通过   2.未通过   3.未审核(默认)  4.已撤销， 5已删除 6.已违规
     */
    public function detail($id, $status = null, $field = null)
    {
        if (empty($field)) {
            $field = ['id', 'act_id', 'user_id', 'title', 'cover', 'img', 'thumb_img', 'width', 'height', 'size', 'ratio', 'browse_num', 'vote_num', 'status', 'reason', 'way', 'create_time'];
        }
        $res = $this->select($field)
            ->where(function ($query) use ($status) {
                if ($status) {
                    $status = !is_array($status) ? explode(',', $status) : $status;
                    $query->whereIn('status', $status);
                }
            })
            ->whereNotIn('status', [5, 6]) //删除和违规的图片都不允许看
            ->where('is_del', 1)
            ->where('id', $id)
            ->first();

        return $res;
    }


    /**
     * 获取下一个未审核的作品
     */
    public function getNextUnchecked($id, $act_id, $keywords, $start_time, $end_time, $sort)
    {
        $res = $this->select('id', 'title')
            ->where(function ($query) use ($start_time, $end_time) {
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->orWhere('serial_number', 'like', '%' . $keywords . '%')
                        ->orWhere('title', 'like', '%' . $keywords . '%');
                }
            })
            ->where('act_id', $act_id)
            ->where('status', 3)
            ->where('id', '<', $id)
            ->where('is_del', 1)
            ->orderByRaw($sort)
            ->first();

        return $res;
    }
    /**
     * 计算某个用户上传的作品数量，超过限制，不允许在继续上传
     * @param user_id 用户id
     * @param way 上传方式  1 前台上传  2 后台上传
     */
    public function getUserWorksNumber($act_id, $user_id = null, $way = null)
    {
        return $this->where('act_id', $act_id)
            ->where(function ($query) use ($way) {
                if ($way) {
                    $query->where('way', $way);
                }
            })
            ->where(function ($query) use ($user_id) {
                if ($user_id) {
                    $query->where('user_id', $user_id);
                }
            })
            ->whereIn('status', [1, 2, 3, 4])
            ->where('is_del', 1)
            ->count();
    }
}
